#!/bin/bash
# File Name: build_pt_comm.sh
# Author: moshan
# mail: mo_shan@yeah.net
# Created Time: 2019-02-22 16:55:51
# Function: 根据需求生成pt命令
#########################################################################
:<<comment
变量注释:
db_name       : 业务库的库名，一般为'mafengwo'，要根据实际情况配置;
mysql_user    : 连接mysql用户名;
mysql_passwd  : 连接mysql的密码;
mysql_port    : 节点的端口号;
mysql_host    : 需要修复的节点的ip地址
test_file     : 该文件会保存着pt的dry-run动作命令，可作为修复主键前的测试阶段。
需要在当前目录编辑一个table.log的文件, 文件格式如下
table1:add:id
table2:modify:id
#注释：表示给table1新添一个id字段作为主键字段，给table2表的id(已经存在的字段)字段更改为主键字段
comment
db_name="db_name"
mysql_user="mysql_user"
mysql_passwd="mysql_passwd"
mysql_port="xxxx"
mysql_host="172.18.8.xxx"
test_file="test.pt"
[ ! -d "${db_name}" ] && mkdir -p ${db_name}
> ${db_name}/${test_file}
sed -n '1,5p' $0|sed "s#${0}#${test_file}#g" > ${db_name}/${test_file}
for i in $(cat table.log)
do
        table_name="$(awk -F: '{print $1}' <<< "${i}")"
        opt="$(awk -F: '{print $2}' <<< "${i}")"
        col="$(awk -F: '{print $3}' <<< "${i}")"
        if [ "${opt}x" == "addx" ]
        then
                opt="add column ${col} int NOT NULL AUTO_INCREMENT primary key"
                opt_log="add column and primary key"
        elif [ "${opt}x" == "modifyx" ]
        then
                opt_log="add primary key"
                opt="add primary key(${col})"
        else
                continue
        fi
        [ "${col}x" == "x" ] && continue
        sed -n '1,5p' $0|sed "s#${0}#${test_file}#g" > ${db_name}/${table_name}.pt
        echo "pt-online-schema-change --check-interval=2  --alter=\"${opt}\" --no-check-replication-filters --check-alter --max-load=\"Threads_running=200\" --critical-load=\"Threads_running=500\" --recurse=0 --ask-pass --dry-run --print h=${mysql_host},P=${mysql_port},u=${mysql_user},p='${mysql_passwd}',D=${db_name},t=${table_name},A=utf8" >> ${db_name}/${table_name}.pt
        echo "[ \$? -ne 0 ] && echo -e \"\033[31m[test] ${opt_log} for ${table_name}:error\033[0m\" && exit" >> ${db_name}/${table_name}.pt
        sed -n '6,$p' ${db_name}/${table_name}.pt | sed 's/&& exit//g;s#$# 2>/dev/null#g' >> ${db_name}/${test_file}
        echo "pt-online-schema-change --check-interval=2  --alter=\"${opt}\" --no-check-replication-filters --check-alter --max-load=\"Threads_running=200\" --critical-load=\"Threads_running=500\" --recurse=0 --ask-pass --execute --print h=${mysql_host},P=${mysql_port},u=${mysql_user},p='${mysql_passwd}',D=${db_name},t=${table_name},A=utf8" >> ${db_name}/${table_name}.pt
        echo "[ \$? -ne 0 ] && echo -e \"\033[31m${opt_log} for ${table_name}:error\033[0m\" && exit" >> ${db_name}/${table_name}.pt
done
